Page({
  data: {
    item: "",
    list: [],
    logs: [],
    leftCount: 0,
    allCompleted: false
  },

  onLoad() {
    var list = wx.getStorageSync("list")
    if (list) {
      var leftCount = list.filter(function(item) {
        return !item.completed
      }).length
      this.setData({ list, leftCount })
    }
    var logs = wx.getStorageSync("logs")
    if (logs) {
      this.setData({ logs })
    }
  },

  save() {
    wx.setStorageSync("list", this.data.list)
    wx.setStorageSync("logs", this.data.logs)
  },

  onInputChange(e) {
    this.setData({ item: e.detail.value })
  },

  onAddItem() {
    if (!this.data.item || !this.data.item.trim()) return
    let list = this.data.list
    list.push({ name: this.data.item, completed: false })
    let logs = this.data.logs
    logs.push({ timestamp: new Date(), action: "Add", name: this.data.item })
    this.setData({
      item: "",
      list,
      logs,
      leftCount: this.data.leftCount + 1
    })
    this.save()
  },

  onToggle(e) {
    var index = e.currentTarget.dataset.index
    var list = this.data.list
    list[index].completed = !list[index].completed
    console.log(list[index])
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: list[index].completed ? "Finish" : "Restart",
      name: list[index].name
    })
    this.setData({
      list,
      logs,
      leftCount: this.data.leftCount + (list[index].completed ? -1 : 1)
    })
    this.save()
  },

  onRemove(e) {
    let index = e.currentTarget.dataset.index
    let list = this.data.list
    let remove = list.splice(index, 1)[0]
    let logs = this.data.logs
    logs.push({ timestamp: new Date(), action: "Remove", name: remove.name })
    this.setData({
      list,
      logs
    })
    this.save()
  },

  onToggleAll() {
    this.data.allCompleted = !this.data.allCompleted
    let list = this.data.list
    list.forEach(v => {
      v.completed = this.data.allCompleted
    })
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: this.data.allCompleted ? "Finish" : "Restart",
      name: "All todos"
    })
    this.setData({
      list,
      logs,
      leftCount: this.data.allCompleted ? 0 : list.length
    })
    this.save()
  },

  onClear() {
    let list = this.data.list
    let filter = list.filter(v => {
      return !v.completed
    })
    this.setData({
      list: filter,
      leftCount: this.data.allCompleted ? 0 : filter.length
    })
    var logs = this.data.logs
    logs.push({
      timestamp: new Date(),
      action: "Clear",
      name: "Completed todo"
    })
    this.save()
  }
})
